/*
 * Copyright 2007 Jeffrey Palm.
 */

import java.awt.*;
import java.io.*;
import java.net.*;
import java.util.*;
import java.util.List;
import javax.swing.*;

class Util {

  private Util() {}

  private static File itunesDir;
  public static File getItunesDir() {
    if (itunesDir == null) {
      String home = System.getProperty("user.home");
      File homeDir = new File(home);     
      if (OS.isMac()) {
        itunesDir = newDir(homeDir, new String[]{"Music","iTunes"});
      } else if (OS.isWindows()) {
        itunesDir = newDir(homeDir,new String[]{"My Documents","My Music","iTunes"});
      } else {
        throw new RuntimeException("Don't know where the iTunes dir is!");
      }
    }
    return itunesDir;
  }
  
  public static File getItunesLibrary() {
    return new File(Util.getItunesDir(),"iTunes Music Library.xml");
  }

  public static File newDir(String dirName) {
    return newDir(null,dirName);
  }
  
  public static File newDir(File parent, String[] names) {
    File dir = parent;
    for (int i=0; i<names.length; i++) {
      dir = newDir(dir,names[i]);
    }
    return dir;
  }
  
  public static File newDir(File parent, String name) {
    File dir;
    if (parent == null) {
      dir = new File(name);
    } else {
      dir = new File(parent,name);
    }
    if (!dir.exists()) {
      dir.mkdirs();
    }
    if (!dir.isDirectory()) {
      throw new IllegalArgumentException(parent + "/" + name + " isn't a directory!");
    }
    return dir;
    
  }

  public static boolean isEmpty(String s) {
    return s == null || s.equals("");
  }

  public static void handle(Object who, Throwable e) {
    System.err.println("EXCEPTION: " + who + ":" + e.getMessage());
    e.printStackTrace();
  }

  public static File wget(String url, File f) throws Exception {
    byte[] buf = new byte[1028];
    InputStream in = new BufferedInputStream(new URL(url).openStream());
    OutputStream out = new BufferedOutputStream(new FileOutputStream(f));
    for (int len = 0; (len = in.read(buf)) != -1;) {
      out.write(buf,0,len);
    }
    out.close();
    in.close();
    return f;
  }

  static void note(Object who, Object msg) {
    System.out.println("[" + who.getClass().getName() + "] " + msg);
  }

  static BufferedReader open(Object who, String urlString) throws Exception {
    return open(who,urlString,Collections.EMPTY_MAP);
  } 

  static BufferedReader open(Object who, String urlString, Map props) throws Exception {
    note(who,"url: " + urlString);
    URL url = new URL(urlString);
    HttpURLConnection con = (HttpURLConnection)url.openConnection();
    con.setRequestProperty("User-agent",UserAgents.randomUserAgent());
    if (props != null) {
      for (Iterator it = props.entrySet().iterator(); it.hasNext();) {
        Map.Entry e = (Map.Entry)it.next();
        con.setRequestProperty(String.valueOf(e.getKey()),String.valueOf(e.getValue()));
      }
    }
    con.connect();
    System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
    try {
      for (int i=1;;i++) {
        String key = con.getHeaderFieldKey(i);
        if (key == null || "".equals(key)) break;
        String val = con.getHeaderField(key);
        System.out.println("  " + key + " : " + val);
      }
    } catch (Exception e) {e.printStackTrace();}
    System.out.println("<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<");
    BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
    return in;
  } 

  static BufferedReader open(Object who, File file) throws Exception {
    note(who,"file: " + file);
    BufferedReader in = new BufferedReader(new FileReader(file));
    return in;
  } 

  static void handleError(Throwable t) {
    String msg;
    if (t != null) {
    final StringBuffer sb = new StringBuffer();
      PrintStream out = new PrintStream(new OutputStream() {
          public void write(int b) throws IOException {
            sb.append((char)(b & 0xff));
          }
        });
      t.printStackTrace(out);
      msg = sb.toString();
    } else {
      msg = "Error";
    }
    JOptionPane.showMessageDialog(null,msg,"Error",JOptionPane.ERROR_MESSAGE);
  }

  static void show(JFrame f) {
    f.pack();
    CenterHelper.center(f);
    f.setVisible(true);
  }

  static JPanel xp() {return gp(BoxLayout.X_AXIS);}
  static JPanel yp() {return gp(BoxLayout.Y_AXIS);}

  static JPanel gp(int axis) {
    JPanel p = new JPanel();
    p.setLayout(new BoxLayout(p,axis));
    return p;
  }

  static JPanel lp() {
    JPanel p = new JPanel();
    p.setLayout(new FlowLayout(FlowLayout.LEFT));
    return p;
  }

  static JPanel lp(Component c) {
    JPanel p = lp();
    p.add(c);
    return p;
  }

  static void showError(Object msg) {
    showError(null,msg);
  }

  static void showError(Component c, Object msg) {
    JOptionPane.showMessageDialog(c,msg,"Error",JOptionPane.ERROR_MESSAGE);
  }

  static void showMsg(Object msg) {
    showMsg(msg,"Information");
  }

  static void showMsg(Object msg, String title) {
    showMsg(null,msg,title);
  }

  static void showMsg(Component c, Object msg, String title) {
    JOptionPane.showMessageDialog(c,msg,title,JOptionPane.INFORMATION_MESSAGE);
  }

  /**
   * Returns just text.
   */
  static String removeTags(String s) {
    if (s == null) return null;
    StringBuffer res = new StringBuffer();
    boolean inTag = false;
    for (int i=0; i<s.length(); i++) {
      char c = s.charAt(i);
      if (c == '<') {
        inTag = true;
      } else if (c == '>') {
        inTag = false;
      } else if (!inTag) {
        res.append(c);
      }
    }
    return res.toString();
  }

  /**
   * Splits <code>subject</code> at <code>delim</code>.  This isn't in 1.3
   */
  static List split(String subject, String delim) {
    List res = new ArrayList();
    if (subject == null) return res;
    if (delim == null) return res;
    int i;
    for (i=0; i<subject.length();) {
      int index = subject.indexOf(delim,i);
      if (index == -1) break;
      res.add(subject.substring(i,index));
      i = index + delim.length();
    }
    if (i<subject.length()) res.add(subject.substring(i));
    return res;
  }

}
